package dk.Interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import com.ReturnData.ResponseData;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import dk.config.SpringContextUtils;
import dk.service.TokenService;



public class MyInterceptor implements HandlerInterceptor{
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
    	//处理文件上传权限问题
    	System.out.println(request.getMethod().toUpperCase());
    	//处理拦截器跨域
    	if("OPTIONS".equals(request.getMethod().toUpperCase())) {
    	    System.out.println("Method:OPTIONS");
    		return true;
    	 }
    	//处理乱码
    	request.setCharacterEncoding("UTF-8");
    	response.setContentType("text/html;charset=utf-8");
        System.out.println("==========拦截到请求 进行鉴权 ====");
        
    	ResponseData data = new ResponseData();
        String Admintoken = request.getHeader("AdminToken");
        String token = request.getHeader("token");
        System.out.println("Admintoken"+Admintoken);
        System.out.println("token"+token);
        //去token服务查
        TokenService tokenservice = (TokenService) SpringContextUtils.getBeanByClass(TokenService.class);
        if(Admintoken!= null) {
        	Integer adminid = tokenservice.GetIdByAdmintoken(Admintoken);
        	Integer id = tokenservice.GetIdByToken(token);
            //如果id存在
           if(id!= null && adminid!=null) {
            	//放行
        	   System.out.println("放行");
            	return true;
            }
        	System.out.println(id);
          
        	
        }
        data.setCode(403);
    	data.setMessage("获取信息失败请检查登录状态");
    	String mes = String.valueOf(JSONArray.toJSON(data));
    	System.out.println(mes);
    	response.getWriter().write(mes);
    	//返回数据
    	
    	System.out.println("==========拦截器结束 ====");
        return false;
        
        
        
        
        
    }

 

}